#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
#include "elf.h"
#include "fs.h"
#include "file.h"
#include "fcntl.h"


#define T_FILE 2
#define T_DIR  1

//static const char* IN_SWAPPER = "inSwapper";
struct {
	struct spinlock lock;
	struct proc proc[NPROC];
} ptable;
struct shmseg{
	int key;
	char* pages[MAX_PAGES];
	int numOfPages;
	struct proc* procs[NPROC];
	int numOfProcs;
} ;
struct shmseg segArray[MAX_SEG];
int nextSegId=0;

static struct proc *initproc;
struct proc *inSwapperProc;


int nextpid = 1;
int swapFlag = 0 ;
int    isInSwapperWorking = 0;
int    wakeupInswapperFlag = 0;

int Debug = 1;


extern void forkret(void);
extern void trapret(void);

extern void inswapper(void);

static void wakeup1(void *chan);
extern int getNumOfFreePages(void);
extern int fileopen(char *path ,int omode , struct file** sf);
extern int fclose(struct file *f, int fd);
extern pte_t* myWalkpgdir(pde_t *pgdir, const void *va, int create);
extern int myMappages(pde_t *pgdir, void *la, uint size, uint pa, int perm);

static int swapOut(struct proc* );
static void createInternalProcess(const char* , void (*)());


void itoa(int n, char* dest);
int unlink(char *path);



void
pinit(void)
{
	initlock(&ptable.lock, "ptable");
}

//PAGEBREAK: 32
// Look in the process table for an UNUSED proc.
// If found, change state to EMBRYO and initialize
// state required to run in the kernel.
// Otherwise return 0.
static struct proc*
allocproc(void)
{
	struct proc *p;
	char *sp;

	acquire(&ptable.lock);
	for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
		if(p->state == UNUSED)
			goto found;
	release(&ptable.lock);
	return 0;

	found:
	p->state = EMBRYO;
	p->pid = nextpid++;
	release(&ptable.lock);

	// Allocate kernel stack.
	if((p->kstack = kalloc()) == 0){
		p->state = UNUSED;
		return 0;
	}
	sp = p->kstack + KSTACKSIZE;

	// Leave room for trap frame.
	sp -= sizeof *p->tf;
	p->tf = (struct trapframe*)sp;

	// Set up new context to start executing at forkret,
	// which returns to trapret.
	sp -= 4;
	*(uint*)sp = (uint)trapret;

	sp -= sizeof *p->context;
	p->context = (struct context*)sp;
	memset(p->context, 0, sizeof *p->context);
	p->context->eip = (uint)forkret;

	return p;
}

//PAGEBREAK: 32
// Set up first user process.
void
userinit(void)
{
	struct proc *p;
	extern char _binary_initcode_start[], _binary_initcode_size[];

	p = allocproc();
	initproc = p;
	if((p->pgdir = setupkvm(kalloc)) == 0)
		panic("userinit: out of memory?");
	inituvm(p->pgdir, _binary_initcode_start, (int)_binary_initcode_size);
	p->sz = PGSIZE;
	memset(p->tf, 0, sizeof(*p->tf));
	p->tf->cs = (SEG_UCODE << 3) | DPL_USER;
	p->tf->ds = (SEG_UDATA << 3) | DPL_USER;
	p->tf->es = p->tf->ds;
	p->tf->ss = p->tf->ds;
	p->tf->eflags = FL_IF;
	p->tf->esp = PGSIZE;
	p->tf->eip = 0;  // beginning of initcode.S

	safestrcpy(p->name, "initcode", sizeof(p->name));
	p->cwd = namei("/");

	p->state = RUNNABLE;
}

// Grow current process's memory by n bytes.
// Return 0 on success, -1 on failure.
int
growproc(int n)
{
  uint sz;

  acquire(&ptable.lock);

  sz = proc->sz;
  if(n > 0){
    if((sz = allocuvm(proc->pgdir, sz, sz + n)) == 0)
    {
      release(&ptable.lock);
      return -1;
    }
  }
  else if(n < 0)
  {
    if((sz = deallocuvm(proc->pgdir, sz, sz + n)) == 0)
    {
      release(&ptable.lock);
      return -1;
    }
  }
  proc->sz = sz;
  release(&ptable.lock);
  switchuvm(proc);

  return 0;
}

// Create a new process copying p as the parent.
// Sets up stack to return as if from system call.
// Caller must set state of returned proc to RUNNABLE.
int
fork(void)
{
  int i, pid;
  struct proc *np;

  // Allocate process.
  if((np = allocproc()) == 0)
    return -1;

  acquire(&ptable.lock);
  // Copy process state from p.
  if((np->pgdir = copyuvm(proc->pgdir, proc->sz)) == 0){
    kfree(np->kstack);
    np->kstack = 0;
    np->state = UNUSED;
    release(&ptable.lock);
    return -1;
  }
  np->sz = proc->sz;
  np->parent = proc;
  *np->tf = *proc->tf;

  // Clear %eax so that fork returns 0 in the child.
  np->tf->eax = 0;

  for(i = 0; i < NOFILE; i++)
    if(proc->ofile[i])
      np->ofile[i] = filedup(proc->ofile[i]);
  np->cwd = idup(proc->cwd);

  pid = np->pid;
  np->state = RUNNABLE;
  safestrcpy(np->name, proc->name, sizeof(proc->name));
  release(&ptable.lock);
  return pid;
}

// Exit the current process.  Does not return.
// An exited process remains in the zombie state
// until its parent calls wait() to find out it exited.
void
exit(void)
{
	struct proc *p;
	int fd;
//	cprintf("exit 1 name: %d, pid:  <%d>  \n\n",proc->name,proc->pid);
	if(proc == initproc)
		panic("init exiting");

	// Close all open files.
	for(fd = 0; fd < NOFILE; fd++){
		if(proc->ofile[fd]){
			fileclose(proc->ofile[fd]);
			proc->ofile[fd] = 0;
		}
	}

	iput(proc->cwd);
	proc->cwd = 0;

	acquire(&ptable.lock);

	// Parent might be sleeping in wait().
	wakeup1(proc->parent);

	// Pass abandoned children to init.
	for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
		if(p->parent == proc){
			p->parent = initproc;
			if(p->state == ZOMBIE)
				wakeup1(initproc);
		}
	}

	// Jump into the scheduler, never to return.
	proc->state = ZOMBIE;
//	cprintf("exit 2 name: %d, pid:  <%d>  \n\n",proc->name,proc->pid);
	sched();
	panic("zombie exit");
}

// Wait for a child process to exit and return its pid.
// Return -1 if this process has no children.
int
wait(void)
{
	struct proc *p;
	int havekids, pid;

	acquire(&ptable.lock);
	for(;;){
		// Scan through table looking for zombie children.
		havekids = 0;
		for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
			if(p->parent != proc)
				continue;
			havekids = 1;
			if(p->state == ZOMBIE){
				// Found one.
				pid = p->pid;
				kfree(p->kstack);
				p->kstack = 0;
				freevm(p->pgdir);
				p->state = UNUSED;
				p->pid = 0;
				p->parent = 0;
				p->name[0] = 0;
				p->killed = 0;
				release(&ptable.lock);
				return pid;
			}
		}

		// No point waiting if we don't have any children.
		if(!havekids || proc->killed){
			release(&ptable.lock);
			return -1;
		}

		// Wait for children to exit.  (See wakeup1 call in proc_exit.)
		sleep(proc, &ptable.lock);  //DOC: wait-sleep
	}
}

void
register_handler(sighandler_t sighandler)
{
	char* addr = uva2ka(proc->pgdir, (char*)proc->tf->esp);
	if ((proc->tf->esp & 0xFFF) == 0)
		panic("esp_offset == 0");

	/* open a new frame */
	*(int*)(addr + ((proc->tf->esp - 4) & 0xFFF))
        										  = proc->tf->eip;
	proc->tf->esp -= 4;

	/* update eip */
	proc->tf->eip = (uint)sighandler;
}


//PAGEBREAK: 42
// Per-CPU process scheduler.
// Each CPU calls scheduler() after setting itself up.
// Scheduler never returns.  It loops, doing:
//  - choose a process to run
//  - swtch to start running that process
//  - eventually that process transfers control
//      via swtch back to the scheduler.
void
scheduler(void)
{
  struct proc *p;

  createInternalProcess("inswapper", &inswapper);

  for(;;){

    // Enable interrupts on this processor.
    sti();

    // Loop over process table looking for process to run.
    acquire(&ptable.lock);

    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
    {
      if(p->state != RUNNABLE && p->state != RUNNABLE_SUSPENDED)
        continue;

      //when p is inswapper process but all other process is not need to swap-in
      if(p == inSwapperProc && wakeupInswapperFlag == 0)
        continue;

      //need to swap in memory (wake up inswapper proc)
      else if(p->state == RUNNABLE_SUSPENDED && isInSwapperWorking == 0){
      		isInSwapperWorking = 1;
        	wakeupInswapperFlag = 1;//wake up inswapper proc;
          continue;
      }
      else if(p->state == RUNNABLE_SUSPENDED && isInSwapperWorking == 1)
          continue;

      // Switch to chosen process.  It is the process's job
      // to release ptable.lock and then reacquire it
      // before jumping back to us.
      proc = p;

      switchuvm(p);
      p->state = RUNNING;
      swtch(&cpu->scheduler, proc->context);
      switchkvm();

      // Process is done running for now.
      // It should have changed its p->state before coming back.
      proc = 0;
    }
    release(&ptable.lock);

  }
}

// Enter scheduler.  Must hold only ptable.lock
// and have changed proc->state.
void
sched(void)
{
	int intena;

	if(!holding(&ptable.lock))
		panic("sched ptable.lock");
	if(cpu->ncli != 1)
		panic("sched locks");
	if(proc->state == RUNNING)
		panic("sched running");
	if(readeflags()&FL_IF)
		panic("sched interruptible");
	intena = cpu->intena;

	swtch(&proc->context, cpu->scheduler);
	cpu->intena = intena;
}

// Give up the CPU for one scheduling round.
void
yield(void)
{
	acquire(&ptable.lock);  //DOC: yieldlock
	proc->state = RUNNABLE;
	sched();
	release(&ptable.lock);
}

// A fork child's very first scheduling by scheduler()
// will swtch here.  "Return" to user space.
void
forkret(void)
{
	static int first = 1;
	// Still holding ptable.lock from scheduler.
	release(&ptable.lock);

	if (first) {
		// Some initialization functions must be run in the context
		// of a regular process (e.g., they call sleep), and thus cannot
		// be run from main().
		first = 0;
		initlog();
	}

	// Return to "caller", actually trapret (see allocproc).
}

//// Atomically release lock and sleep on chan.
//// Reacquires lock when awakened.
//void
//sleep(void *chan, struct spinlock *lk)
//{
//  if(proc == 0)
//    panic("sleep");
//
//  if(lk == 0)
//    panic("sleep without lk");
//
//  // Must acquire ptable.lock in order to
//  // change p->state and then call sched.
//  // Once we hold ptable.lock, we can be
//  // guaranteed that we won't miss any wakeup
//  // (wakeup runs with ptable.lock locked),
//  // so it's okay to release lk.
//  if(lk != &ptable.lock){  //DOC: sleeplock0
//    acquire(&ptable.lock);  //DOC: sleeplock1
//    release(lk);
//  }
//
//  // Go to sleep.
//  proc->chan = chan;
//  proc->state = SLEEPING;
//
//  if(swapFlag)
//      if(proc->pid > 2 )
//         swapOut(proc);
//
//
//  sched();
//
//  // Tidy up.
//  proc->chan = 0;
//  if(swapFlag == 1 )
//  {
//     if(proc->state == SLEEPING_SUSPENDED)
//        proc->state = RUNNABLE_SUSPENDED;
//  }
//  else
//  {
//    proc->state = RUNNABLE;
//
//    struct proc *p;
//
//    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
//    {
//      if(p->state == SLEEPING_SUSPENDED)
//        p->state = RUNNABLE_SUSPENDED;
//    }
//    p = 0 ;
//    isInSwapperWorking = 1;
//    wakeupInswapperFlag = 1;//wake up inswapper proc;
//
//  }
//
//
//  // Reacquire original lock.
//  if(lk != &ptable.lock){  //DOC: sleeplock2
//    release(&ptable.lock);
//    acquire(lk);
//  }
//}

// Atomically release lock and sleep on chan.
// Reacquires lock when awakened.
void
sleep(void *chan, struct spinlock *lk)
{
  if(proc == 0)
    panic("sleep");

  if(lk == 0)
    panic("sleep without lk");

  // Must acquire ptable.lock in order to
  // change p->state and then call sched.
  // Once we hold ptable.lock, we can be
  // guaranteed that we won't miss any wakeup
  // (wakeup runs with ptable.lock locked),
  // so it's okay to release lk.
  if(lk != &ptable.lock){  //DOC: sleeplock0
    acquire(&ptable.lock);  //DOC: sleeplock1
    release(lk);
  }

  // Go to sleep.
  proc->chan = chan;
  proc->state = SLEEPING;

  if(swapFlag == 1 && proc->pid > 2 )
         swapOut(proc);


  sched();

  // Reacquire original lock.
  if(lk != &ptable.lock){  //DOC: sleeplock2
    release(&ptable.lock);
    acquire(lk);
  }
}


//PAGEBREAK!
// Wake up all processes sleeping on chan.
// The ptable lock must be held.
static void
wakeup1(void *chan)
{
  struct proc *p;

  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)
  {
    if(swapFlag)
    {
      if (p->state == SLEEPING && p->chan == chan)
        p->state = RUNNABLE;

      if(p->state == SLEEPING_SUSPENDED && p->chan == chan)
        p->state = RUNNABLE_SUSPENDED;
    }
    else
        if(p->state == SLEEPING && p->chan == chan)
          p->state = RUNNABLE;

  }
}


// Wake up all processes sleeping on chan.
void
wakeup(void *chan)
{
	acquire(&ptable.lock);
	wakeup1(chan);
	release(&ptable.lock);
}

// Kill the process with the given pid.
// Process won't exit until it returns
// to user space (see trap in trap.c).
int
kill(int pid)
{
	struct proc *p;

	acquire(&ptable.lock);
	for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
		if(p->pid == pid){
			p->killed = 1;
			// Wake process from sleep if necessary.
			if(p->state == SLEEPING)
				p->state = RUNNABLE;
			release(&ptable.lock);
			return 0;
		}
	}
	release(&ptable.lock);
	return -1;
}

//PAGEBREAK: 36
// Print a process listing to console.  For debugging.
// Runs when user types ^P on console.
// No lock to avoid wedging a stuck machine further.
void
procdump(void)
{
	static char *states[] = {
			[UNUSED]    "unused",
			[EMBRYO]    "embryo",
			[SLEEPING]  "sleep ",
			[RUNNABLE]  "runble",
			[RUNNING]   "run   ",
			[ZOMBIE]    "zombie",
			[SLEEPING_SUSPENDED] "sleeping_suspended",
			[RUNNABLE_SUSPENDED] "runnable_suspended"
	};
	int i;
	struct proc *p;
	char *state;
	uint pc[10];

	for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
		if(p->state == UNUSED)
			continue;
		if(p->state >= 0 && p->state < NELEM(states) && states[p->state])
			state = states[p->state];
		else
			state = "???";
		cprintf("%d %s %s", p->pid, state, p->name);
		if(p->state == SLEEPING){
			getcallerpcs((uint*)p->context->ebp+2, pc);
			for(i=0; i<10 && pc[i] != 0; i++)
				cprintf(" %p", pc[i]);
		}
		cprintf("\n");
	}
}

//------------------------------ TASK 1 ----------------------
//note: look like userinit.
static void
createInternalProcess(const char *name, void (*entrypoint)())
{
  struct proc *p;
  extern char _binary_initcode_start[], _binary_initcode_size[];

  p = allocproc();
  p->context->eip = (uint)entrypoint;

  if(!(p->pgdir = setupkvm()))
    panic("createInternalProcess: out of memory?");

  //Load the initcode .
  inituvm(p->pgdir, _binary_initcode_start, (int)_binary_initcode_size);
  p->sz = PGSIZE;

  safestrcpy(p->name, name, sizeof(p->name));
  p->cwd = namei("/");

  p->state = RUNNABLE;

  inSwapperProc = p;

}
static int swapOut(struct proc* p)
{
  int fd, i;
  char fileName[10];
  struct file *f;
  pde_t *pgtab;


  //get the file name to swap out
  itoa(p->pid, fileName);

  if(Debug == 1)
    cprintf("proc %d start swapOut. fileSwap:%s \n",p->pid,fileName);


  release(&ptable.lock);

  // Create a swap file for the selected process
  if((fd = fileopen(fileName, 0x200 | 0x001, &f)) < 0) { // O_CREATE | O_WRONLY

    cprintf("swap_out: can't open file %s\n", fileName);
    panic("swapOut\n");
  }

  acquire(&ptable.lock);



  if(p->pgdir == 0)
    panic("swapOut: pgdir is null");

  release(&ptable.lock);


//2. for each user page of the process' pages:
  for(i = 0; i < p->sz; i+=PGSIZE)
  {
    pgtab = myWalkpgdir(p->pgdir, (const void *)i , 0);

    //2.1. Write the current page to the swap file
    filewrite(f, (char*)p2v(PTE_ADDR(*pgtab)), PGSIZE);
  }

  fclose(f, fd);

  acquire(&ptable.lock);
//3. Free the user pages

  deallocuvm(p->pgdir, KERNBASE, 0);

  p->pgdir = 0;

  p->state = SLEEPING_SUSPENDED;


  if(Debug == 1)
    cprintf("proc %d Finish swap_out. fileSwap:%s \n",p->pid,fileName);

  return 0;
}

int enableSwapping()
{
	return swapFlag = 1;
}
int disableSwapping()
{
	return swapFlag = 0;
}

//------------------- Task 2 -------------------------


//returns the identifier of the shared memory segment associated with the
//value of the argument key.
int shmget(int key,uint size, int shmflg)
{

	int i;
	if (shmflg == GET)
	{
		for (i = 0; i < nextSegId ; i++)
			if(segArray[i].key == key)
				return i;
		return -1;
	}

	if (shmflg == CREAT)
	{
		for (i = 0; i<nextSegId ; i++)
			if(segArray[i].key == key)
				return -1;
		if (size % 4096  == 0)
			segArray[nextSegId].numOfPages = size / 4096;	//num of pages(each size 4096)
		else
			segArray[nextSegId].numOfPages = size / 4096 + 1;	//add another page

		for (i=0 ; i < segArray[nextSegId].numOfPages ; i++)	//Allocate all pages
		{
			segArray[nextSegId].pages[i] = kalloc();
		}
		segArray[nextSegId].key = key;
		nextSegId++;
		return nextSegId - 1;
	}
	return -1;
}

//If the shared memory mapped to shmid is not linked to any other process, the kernel
//free the previously allocated frames and return the number of frames freed.
//Otherwise, it returns -1.v
int shmdel(int shmid)
{
	int i;
	if (shmid > nextSegId)
		return -1;
	else
		if (segArray[shmid].numOfProcs == 0)
		{
			for(i=0;i<segArray[shmid].numOfPages;i++)//free the memory
			{

				kfree(segArray[shmid].pages[i]);
			}
			segArray[shmid].numOfPages=0;
			return i;
		}
		else
			return -1;
}

//shmat() attaches the shared memory segment identified by shmid to the address
//space of the calling process. The system chooses a suitable (unused) address at which
//to attach the segment.
//If SHM_RDONLY is specified in shmflg, the segment is attached for reading only. If
//SHM_RDWR is specified in shmflg, the segment is attached for read and write.
//There is no notion of a write-only shared memory segment.
//On success shmat() returns the address of the attached shared memory segment.
//Otherwise -1 is returned.
void *shmat(int shmid,int shmflg)
{
	segArray[shmid].procs[segArray[shmid].numOfProcs] = proc;	//add proc to shm by shmid
	segArray[shmid].numOfProcs++;
	int i;
	int flag=0;
	if(shmflg & SHM_RDONLY)
		flag = PTE_U;			//PTE_U = Page table entry flags - user (Hex num)
	else if (shmflg & SHM_RDWR)
		flag = PTE_W|PTE_U;		//PTE_W = Page table entry flags - Writeable
	else
		return (void*)-1;
	int sz = proc->sz;
	for (i = 0; i < segArray[shmid].numOfPages; i++)
	{
		myMappages(proc->pgdir,(void*)proc->sz,PGSIZE,v2p(segArray[shmid].pages[i]), flag);
		proc->sz += PGSIZE;
	}
	proc->shmids[proc->next] = shmid;
	proc->locs[proc->next] = (void*)sz;
	proc->next++;

	return (void*)sz;
}

//called from shmdt.
int deleteShmFromProc(pde_t *pgdir ,const void* end, const void* start)
{

	pte_t *pte;

	for(; start  < end; start += PGSIZE){
		pte = myWalkpgdir(pgdir, (char*)start, 0);
		*pte = 0;
	}

	return 0;
}

//shmdt() detaches the shared memory segment located at the address specified by
//shmaddr from the address space of the calling process. The to-be-detached
//segment must be currently attached with shmaddr equal to the value returned by
//the attaching shmat() call.
//On success shmdt() returns 0. Otherwise -1 is returned.
int shmdt(const void*shmaddr)
{
	int i, shmid;
	for(i=0;i<proc->next;i++)
	{
		if(shmaddr==proc->locs[i])
			break;
	}
	if (i==proc->next)
	{

		return -1;		//proc with this shm addr didn't find
	}
	else
	{

		shmid = proc->shmids[i];

		deleteShmFromProc(proc->pgdir,shmaddr+segArray[shmid].numOfPages*PGSIZE,shmaddr);
		segArray[shmid].numOfProcs--;
		proc->locs[i]=0;
		proc->shmids[i]=-1;
		return 0;
	}
}



//--------------------UTILS---------------------------
//
//
////Similar to sys_open on sysfile.c
//struct file* openFile(char *path , int omode)
//{
//
//	struct file *f;
//	struct inode *ip;
//
//
//	if(omode & O_CREATE){
//
//		begin_trans();
//		ip = create(path, T_FILE, 0, 0);
//		commit_trans();
//		if(ip == 0)
//		{
//			return 0;
//
//		}
//	} else {
//		if((ip = namei(path)) == 0)
//		{
//			return 0;
//		}
//		ilock(ip);
//		if(ip->type == T_DIR && omode != O_RDONLY){
//			iunlockput(ip);
//
//			return 0;
//		}
//	}
//
//	if((f = filealloc()) == 0 ){
//		if(f)
//			fileclose(f);
//		iunlockput(ip);
//
//		return 0;
//	}
//	iunlock(ip);
//	f->type = FD_INODE;
//	f->ip = ip;
//	f->off = 0;
//	f->readable =1;
//	f->writable = 1;
//	return f;
//
//	/*
//  cprintf("openfile!!!!!!!!!!!!!!!!!!\n");
//  struct inode* ip;
//  struct file* f;
//
//  f=filealloc();
//  begin_trans();
//
//  if(proc->pid==3)
//  {
//
//    ip = create("oded", T_FILE, 0, 0);
//
//  }
//  if(proc->pid==4)
//  {
//
//    ip = create("oded2", T_FILE, 0, 0);
//
//
//  }
//  commit_trans();
//  f->type = FD_INODE;
//  f->ip = ip;
//  f->off = 0;
//  f->readable = 1;
//  f->writable = 1;
//
//  return f;
//	 */
//}
//
//
//from sys_unlink sysfile.c
int unlink(char *path)
{
	struct inode *ip, *dp;
	struct dirent de;
	char name[DIRSIZ];
	uint off;


	if((dp = nameiparent(path, name)) == 0)
		return -1;

	begin_trans();

	ilock(dp);

	// Cannot unlink "." or "..".
	if(namecmp(name, ".") == 0 || namecmp(name, "..") == 0)
		goto bad;

	if((ip = dirlookup(dp, name, &off)) == 0)
		goto bad;
	ilock(ip);

	if(ip->nlink < 1)
		panic("unlink: nlink < 1");
	memset(&de, 0, sizeof(de));

	if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
		panic("unlink: writei");
	if(ip->type == T_DIR){
		dp->nlink--;
		iupdate(dp);
	}
	iunlockput(dp);

	ip->nlink--;
	iupdate(ip);
	iunlockput(ip);

	commit_trans();

	return 0;

	bad:
	iunlockput(dp);
	commit_trans();
	return -1;
}

//integer to char array
void itoa(int n, char* dest)
{
	char out[10];
	int i = 0, j = 0, k = 0;
	char tmp;
	if (n == 0) {
		out[i++] = '0';
	}
	while (n > 0) {
		out[i++] = '0' + n % 10;
		n /= 10;
	}
	k = i-1;

	while (j < k)
	{
		tmp = out[j];
		out[j] = out[k];
		out[k] = tmp;
		j++;
		k--;
	}
	out[i++] = '.';
	out[i++] = 's';
	out[i++] = 'w';
	out[i++] = 'a';
	out[i++] = 'p';
	out[i++] = '\0';
	safestrcpy(dest,out,i);

}
//

